package org.luxor.common.netty.jdk.aio.server.handler;

import org.luxor.commons.core.utils.DateUtils;
import org.luxor.commons.core.utils.IoUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * 读取 客户端消息
 *
 * @author Mr.yan @date 2023/9/3
 */
public class ServerReadCompletionHandler implements CompletionHandler<Integer, ByteBuffer> {
    private static final Logger log = LoggerFactory.getLogger(ServerReadCompletionHandler.class);

    private AsynchronousSocketChannel channel;

    public ServerReadCompletionHandler(AsynchronousSocketChannel channel) {
        if (channel != null) {
            this.channel = channel;
        }
    }

    @Override
    public void completed(Integer result, ByteBuffer readBuffer) {
        // 接收消息
        readBuffer.flip();
        byte[] body = new byte[readBuffer.remaining()];
        readBuffer.get(body);
        String req = new String(body, StandardCharsets.UTF_8);
        System.out.println("The time server receive order:" + req);

        // 响应消息
        String response = "QUERY TIME ORDER".equalsIgnoreCase(req) ? DateUtils.format(new Date(), DateUtils.DATE_FORMAT_19_FORWARD_SLASH) : "BAD ORDER";
        byte[] bytes = response.getBytes();
        ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length);
        writeBuffer.put(bytes);
        writeBuffer.flip();
        channel.write(writeBuffer, writeBuffer, new ServerWriteCompletionHandler(this.channel));
    }

    @Override
    public void failed(Throwable exc, ByteBuffer byteBuffer) {
        log.error("读取对端消息，失败", exc);
        IoUtils.closeQuietly(channel);
    }
}
